package cn.takujo.takujoframework.common.util.code_generator;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.takujo.takujoframework.common.util.code_generator.JavaBean.PrivateField;
import lombok.Data;

@Data
public class MybatisMapper {

	private String interfaceName;
	private String packName;
	private String tableName;
	private String beanTypeStr;
	private String insert;
	private String update;
	private String beanQualifiedPackName;

	public MybatisMapper(String interfaceName, String packName, JavaBean bean) {
		if (interfaceName != null) {
			this.interfaceName = interfaceName;
		} else {
			this.interfaceName = bean.getBeanName();
		}
		this.packName = packName;
		this.tableName = bean.getTableName();
		beanTypeStr = bean.getBeanName();
		beanQualifiedPackName = bean.getPackName() + "." + beanTypeStr;
		PrivateField<?>[] fields = bean.getFields();
		List<PrivateField<?>> asList = new ArrayList<>(Arrays.asList(fields));
		int size = asList.size();
		int j = 0;
		for (int i = 0; i < size; i++) {
			PrivateField<?> pf = asList.get(i);
			if (pf.getColumn().equals("id")) {
				j = i;
			}
		}
		asList.remove(j);
		insert(asList);
		update(asList);
	}

	public void insert(List<PrivateField<?>> fields) {
		StringBuffer sb1 = new StringBuffer("(");
		StringBuffer sb2 = new StringBuffer(" VALUES(");
		int length = fields.size();
		for (int i = 0; i < length; i++) {
			PrivateField<?> field = fields.get(i);
			String column = field.getColumn();
			String name = field.getName();
			if (i == length - 1) {
				sb1.append(column);
				sb2.append(name);
			} else {
				sb1.append(column + ",");
				sb2.append(name + ",");
			}
		}
		insert = sb1.toString() + ")" + sb2.toString() + ")";
	}

	public void update(List<PrivateField<?>> fields) {
		StringBuffer sb = new StringBuffer();
		int length = fields.size();
		for (int i = 0; i < length; i++) {
			PrivateField<?> field = fields.get(i);
			String column = field.getColumn();
			String name = field.getName();
			if (i == length - 1) {
				sb.append(column + "=#{" + name + "}");
			} else {
				sb.append(column + "=#{" + name + "},");
			}
		}
		update = sb.toString();
	}

	public Map<String, Object> toMap() {
		Map<String, Object> map = new HashMap<>();
		map.put("interfaceName", interfaceName);
		map.put("packName", packName);
		map.put("tableName", tableName.toUpperCase());
		map.put("beanTypeStr", beanTypeStr);
		map.put("insert", insert);
		map.put("update", update);
		map.put("beanQualifiedPackName", beanQualifiedPackName);
		return map;
	}

}
